<!DOCTYPE html>
<html>
<head lang="utf-8">
    <meta charset="UTF-8">
    <title>teacher_{{roomID}}</title>
    <meta name="viewport" content="width=device-width,initial-scale=1,user-scalable=0">
    <link rel="stylesheet" href="http://res.wx.qq.com/open/libs/weui/0.4.0/weui.min.css">
    <style>
        * {
            font-family: "微软雅黑";
        }

        html, body {
            height: 100%;
        }

        #content { /* this is the div you want to fill the window */
            min-height: 100%;
        }

        * html #content {
            height: 100%
        }

        .content {
            width: 100%;
            height: 100%;
            margin: auto;
        }

        .chatTitle {
            width: 100%;
            height: 5%;
            text-align: center;
            background-color: #b1a8a8;
        }

        .chatTitle .title {
            font-size: 1.5em;
        }

        .chatArea {
            width: 100%;
            height: 95%;
        }

        .userListOnline {
            width: 25%;
            height: 95%;
            float: left;
            overflow-y: auto;
            background-color: #ccccd2;
        }

        .txtArea {
            width: 75%;
            height: 95%;
            float: left;
            background-color: #f8f8f8;
        }

        .msgArea {
            width: 100%;
            height: 90%;
            overflow-y: auto;
            border-bottom: 1px solid #9d9898;
        }

        .sendArea {
            width: 100%;
            height: 5%;
        }

        .input_msg {
            width: 100%;
            height: 2em;
            font-size: 1.5em;
        }

        .name_msg {
            font-weight: bolder;
        }

        .uname {
            line-height: 25px;
            vertical-align: middle;
        }

        .data_msg {
            margin-left: 5%;
            background-color: #e0e3e6;
            border-radius: 8px;
            padding: 3px;
        }

        ul {
            margin-left: 20%;
        }

        ul li {
            list-style-type: none;
        }

        .sysMsg {
            color: #c1bfbf;
            padding-right: 5px;
            padding-left: 5px;
            font-size: 14px;
        }

        #talkOrShutup {
            width: 80px;
            height: 100%;
        }

        .handup_image {
            margin-left: 10px;
        }

        .connecting_image {
            margin-left: 5px;
            vertical-align: middle;
        }

        .user_li img {
            vertical-align: middle;
        }
        .weui_btn+.weui_btn{
            margin-top: 0;
        }

    </style>
</head>
<body>
<div class="content" id="content">
    <div class="chatTitle button_sp_area" id="chattitle" align="center">
        <button id="talkOrShutup" class="weui_btn weui_btn_mini weui_btn_warn">禁 言</button>
        <button id="talkOrShutup" class="weui_btn weui_btn_mini weui_btn_warn">禁止举手</button>
        <div id="tips"></div>
        <!--<button id="joinOrLeave">退出聊天室</button>-->
    </div>
    <div class="chatArea well">
        <div class="userListOnline">
            <div id="user_operation">
                当前在线人数: <span id="count">{{users.length}}</span>
                <button id="put_down_all_hand" class="weui_btn weui_btn_mini weui_btn_warn" style="display: none;">
                    取消举手
                </button>
                <button id="close_all_connection" class="weui_btn weui_btn_mini weui_btn_warn" style="display: none;">
                    关闭所有连麦
                </button>
            </div>
            <!--<br/>-->
            <div id="userListOnline"></div>
        </div>

        <div class="txtArea" id="txtArea">
            <div class="msgArea" id="msgArea"></div>
            <div class="sendArea">
                <table style="width: 100%">
                    <tr>
                        <td width="90%">
                            <textarea id="messageInput" wrap="soft" class="input_msg" type="text"
                                      placeholder="发送内容。。。       Enter 键发送消息"></textarea>
                        </td>
                        <td style="text-align: center;">
                            <button id="sendMessage" class="weui_btn weui_btn_mini weui_btn_primary send" id="send">发送
                            </button>
                        </td>
                    </tr>
                </table>
            </div>
        </div>
        <div style="clear: both;"></div>
    </div>
</div>

<script src="/socket.io/socket.io.js"></script>
<script src="/js/jquery.js"></script>
<script src="/js/common.js"></script>
<script>

    var socket;
    var userName = '';  //教师姓名
    var count_connect = 0;//学生连麦数量
    var userId = '';
    var isfrom = '';
    var userOnline = {}
    $(function () {


        //处理url参数
        function GetUrlPara() {
            var url = document.location.toString();
            var arrUrl = url.split("/");
            var roomId = arrUrl[arrUrl.length - 1];
            var userInfoArrs = arrUrl[arrUrl.length - 2];
            var userInfos = userInfoArrs.split("&");
            userId = userInfos[0];
            userName = userInfos[1];
            isfrom = userInfos[2];
            userName = decodeURI(userName)

            if (isfrom == undefined) {
                isfrom = 'w'
            }

            console.log('url=' + url)
            console.log(arrUrl)
            console.log(roomId + '' + userInfoArrs)
            console.log('老师：' + userName + '，id=' + userId + '  进入聊天室：' + roomId)
        }

        // ---------创建连接-----------
        socket = io();


        GetUrlPara();

        // 加入聊天室
        socket.on('connect', function () {
            console.log('connection 中的username=' + userName)
            var data = {
                userName: userName,
                userId: userId,
                isfrom: isfrom
            }
            socket.emit('join', data);
        });

        // 监听消息
        socket.on('msg', function (user, msg) {

            var element = '<div class="message">' +
                    '     <div class="name_msg">' +
                    '		<span class="">' + user.name + getdate() + '	</div>' +
                    '   <div class="data_msg">' + msg +
                    '	</div>' + '</div>';
            $('#msgArea').append(element);
            // 滚动条保持最下方
            $('#msgArea').scrollTop($('#msgArea')[0].scrollHeight);
        });

        // 监听系统消息
        socket.on('sys', function (sysMsg, users) {
            //消息不为空的时间显示到聊天页面
            if (sysMsg != '' || sysMsg.length != 0) {
                var message = '<div class="sysMsg">' + sysMsg + '</div>';
                $('#msgArea').append(message);
            }
            $('#count').text(users.length);

            refresh_userlist(users)
        });


        //解除禁言事件
        socket.on('talk', function (msg) {
            $('#talkOrShutup').text('禁 言');
            $('#talkOrShutup').attr('Class', 'weui_btn weui_btn_mini weui_btn_warn')
            $('#messageInput').removeAttr('disabled')
            $('#messageInput').attr('placeholder', '请输入聊天内容。。。      Enter 键发送消息')
        })

        //禁言事件
        socket.on('shutup', function (msg) {
            $('#talkOrShutup').text('聊 天');
            $('#talkOrShutup').attr('Class', 'weui_btn weui_btn_mini weui_btn_primary')
            $('#messageInput').attr('disabled', 'disabled')
            $('#messageInput').attr('placeholder', '禁言中')
        })


        //举手事件
        socket.on('ishandup', function (data, users) {
            if (data.ishandup == 1) {
                refresh_userlist(users)
            } else if (data.ishandup == 0) {
                refresh_userlist(users)
            }
            socket.emit("handup_back", data)
        })


        // 发送消息
        $('#messageInput').keydown(function (e) {
            if (e.which === 13) {
                e.preventDefault();
                var msg = $(this).val();
                if (msg.trim() == '') {
                    return false
                }
                $(this).val('');
                socket.send(msg);
            }
        });

        $('#sendMessage').click(function () {
            var msg = $('#messageInput').val();
            if (msg.trim() == '') {
                return false
            }
            $('#messageInput').val('');
            socket.send(msg);
        })

        // 退出聊天室
        $('#joinOrLeave').click(function () {
            if ($(this).text() === '退出聊天室') {
                $(this).text('进入聊天室');
                socket.emit('leave');
                var msg = '你已经退出了聊天室,重新发言请点击"进入聊天室"';
                $('#msgArea').append('<div class="sysMsg">' + msg + '</div>');
            } else {
                $(this).text('退出聊天室');
                socket.emit('join', userName);
            }
        });

        // 禁言
        $('#talkOrShutup').click(function () {
            if ($(this).text() === '禁 言') {
                $(this).text('聊 天');
                socket.emit('shutup', userName);
            } else {
                $(this).text('禁 言');
                socket.emit('talk', userName);
            }
        });
        // 允许或禁止举手
        $('#hand_up_down').click(function () {
            if ($(this).text() === '举手发言') {
                $(this).text('禁止举手');
                socket.emit('hand_up_down', userName,1);
            } else {
                $(this).text('举手发言');
                socket.emit('hand_up_down', userName,0);
            }
        });

        // 学生回应老师连接状态，0是断开，1是连接
        socket.on('connectingU', function (data) {
            if (data.connect_status == 0) {
                count_connect--
                if (count_connect == 0) {
                    disconnect_all()
                }
                console.log('收到学生的回应' + ' 断开连接。。。')
            } else if (data.connect_status == 1) {
                count_connect++

                connect(data.userId)
                console.log('收到学生的回应' + ' 正在连接。。。')
            }
        });

        // 教师主动断开所有连接，连接数清零
        $("#close_all_connection").click(function () {
            close_all()
        });

        // 教师取消所有举手
        $("#put_down_all_hand").click(function () {
            socket.emit('put_down_all_hand',userName)
        });


    })

    function close_all() {
        socket.emit('disconnect_all_student', userName)
        disconnect_all()
    }

    function connect_me(userId, name) {
        console.log('要求发言的学生姓名：' + name + ';id:' + userId)
        var stu = {
            userId: userId,
            name: name
        }

        if (count_connect < 4) {
            socket.emit('connect_stu', stu)
        } else {
            show_max_connect_tip()
        }
    }

    function disconnect_me(userId, name) {
        console.log('要求发言的学生姓名：' + name + ';id:' + userId)
        var stu = {
            userId: userId,
            name: name
        }
        socket.emit('disconnect_stu', stu)
    }


    function getdate() {
        var date = new Date();
        var year = date.getFullYear(); //获取当前年份
        var mon = date.getMonth() + 1; //获取当前月份
        var da = date.getDate(); //获取当前日
        var day = date.getDay(); //获取当前星期几
        var h = date.getHours(); //获取小时
        var m = date.getMinutes() < 10 ? '0' + date.getMinutes() : date.getMinutes(); //获取分钟
        var s = date.getSeconds() < 10 ? '0' + date.getSeconds() : date.getSeconds(); //获取秒

        return '<span class="sysMsg"> ' + mon + '-' + da + ' ' + h + ':' + m + ':' + s + '</span>';
    }

    /**
     * 显示连接过多通知
     */
    function show_max_connect_tip() {
        $("#talkOrShutup").hide()
        var htmltip = "<label class='red' style='font-size: 26px;line-height: 100%;color: lightpink;'>最多同时连接4个学生 </label>"
        $("#tips").html(htmltip)
        setInterval(function () {
            $("#talkOrShutup").show()
            $("#tips").html("")
        }, 3000);
    }

    /**
     * 刷新房间内人员名单和连麦、举手状态
     * @param users 房间内成员
     */
    function refresh_userlist(users) {
        //初始化数据
        userOnline['weixin'] = []
        userOnline['pad'] = []
        userOnline['others'] = []

        var userListHtml = '<div><ul>';
        userListHtml += '<li class="user_li">' + '<img alt="NoImg" src="/image/tea_icon.png" width="25px" height="25px">' + ' <span class="uname" > ' + userName + '</span></li>'

        //学生连麦标志
        var connect_flag = false;
        //学生举手标志
        var hand_flag = false;

        users.forEach(function (user, index, array) {
            if (user.userId != userId) {
                var imagePage = '';
                if (user.isfrom == 'wc') {//微信
                    userOnline['weixin'].push(user)
                } else if (user.isfrom == 'p') {//pad
                    userOnline['pad'].push(user)
                } else {
                    userOnline['others'].push(user)
                }

                if (user.isconnected == 1) {
                    connect_flag = true
                }
                if (user.ishandup == 1) {
                    hand_flag = true
                }
            }
        });

        if (connect_flag) {
            $("#close_all_connection").show();
        } else {
            $("#close_all_connection").hide();
        }

        if (hand_flag) {
            $("#put_down_all_hand").show();
        } else {
            $("#put_down_all_hand").hide();
        }


        //举手标志，功能暂时未用
        var handup = '<img alt="NoImg" src="/image/handup.png" width="25px" height="25px" class="handup_image">'

        //pad标志，显示连麦功能
        userOnline['pad'].forEach(function (user, index, array) {
            var imagePage = '<img alt="NoImg" src="/image/pad.png" width="25px" height="25px">'

            //未连麦状态
            if (user.isconnected == 0) {
                var connecting = "<img alt=\"NoImg\" src=\"/image/tel.png\" width=\"25px\" height=\"25px\" class=\"connecting_image\" onclick=\"connect_me('" + user.userId + "','" + user.name + "')\">"
            }//连麦状态
            else if (user.isconnected == 1) {
                var connecting = "<img alt=\"NoImg\" src=\"/image/teloff.png\" width=\"25px\" height=\"25px\" class=\"connecting_image\" onclick=\"disconnect_me('" + user.userId + "','" + user.name + "')\">"
            }

            //举手状态
            if (user.ishandup == 1) {
                userListHtml += '<li class="user_li">' + imagePage + ' <span class="uname" > ' + user.name + '</span> &nbsp;&nbsp;' + connecting + handup + '</li>'
            }//没举手
            else {
                userListHtml += '<li class="user_li">' + imagePage + ' <span class="uname" > ' + user.name + '</span> &nbsp;&nbsp;' + connecting + '</li>'
            }
        })


        //wechat图标，
        userOnline['weixin'].forEach(function (user, index, array) {
            var imagePage = '<img alt="NoImg" src="/image/weixin.png" width="25px" height="25px">'
            //   var connecting = '<img alt="NoImg" src="/image/tel.png" width="25px" height="25px" class="connecting_image" onclick="connect_me(user.userId,user.name)">'

            //举手状态
            if (user.ishandup == 1) {
                userListHtml += '<li class="user_li">' + imagePage + ' <span class="uname" > ' + user.name + '</span> &nbsp;&nbsp;' + handup + '</li>'
            }//没举手
            else {
                userListHtml += '<li class="user_li">' + imagePage + ' <span class="uname" > ' + user.name + '</span> &nbsp;&nbsp;' + '</li>'
            }
        })

        //其他方式登录,不显示登录图标
        userOnline['others'].forEach(function (user, index, array) {
            //举手状态
            if (user.ishandup == 1) {
                userListHtml += '<li class="user_li">' + ' <span class="uname" style="margin-left: 28px;"> ' + user.name + '</span> &nbsp;&nbsp;' + handup + '</li>'
            }//没举手
            else {
                userListHtml += '<li class="user_li">'+' <span class="uname" > ' + user.name + '</span> &nbsp;&nbsp;' + '</li>'
            }
        })
        userListHtml += '<ul><div>'
        $('#userListOnline').html(userListHtml);
    }

</script>
</body>
</html>
